package com.atguigu.crowd.config;

import com.atguigu.crowd.entity.Admin;
import com.atguigu.crowd.entity.Role;
import com.atguigu.crowd.mapper.AdminMapper;
import com.atguigu.crowd.mapper.RoleMapper;
import com.atguigu.crowd.service.api.AuthService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Component
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private AdminMapper adminMapper;
    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private AuthService authService;

    ClassPathXmlApplicationContext ioc = new ClassPathXmlApplicationContext("classpath:spring.xml");


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        //用户信息
        Admin admin = adminMapper.selectAdminByUsername(username);
        System.out.println(admin);
        Integer adminId = admin.getId();

        //角色信息
        List<Role> roleList = roleMapper.selectAssignedRole(adminId);
        List<String> roleNameList = roleList.stream().map(Role::getName).collect(Collectors.toList());

        //权限信息
        List<String> authNameList = authService.selectAuthNameByAdminId(adminId);

        //认证集合
        List<GrantedAuthority> authorities = new ArrayList<>();

        for (String roleName : roleNameList) {
            SimpleGrantedAuthority simpleGrantedAuthority = new SimpleGrantedAuthority("ROLE_" + roleName);
            authorities.add(simpleGrantedAuthority);

        }

        for (String authName : authNameList) {
            SimpleGrantedAuthority simpleGrantedAuthority = new SimpleGrantedAuthority(authName);
            authorities.add(simpleGrantedAuthority);
        }

        return new SecurityAdmin(admin, authorities);
    }
}
